package com.trjn.util;

import jpcap.packet.ARPPacket;
import jpcap.packet.EthernetPacket;

import java.net.InetAddress;

/**
 * ARPPacket Build
 * @author : XieDong
 * @date : 2019/1/10 11:00
 */
public class ArpPacketBuilder {


    private static ARPPacket builder(){
        //修改目标的ARP表的ARP包
        ARPPacket arp = new ARPPacket();
        //选择以太网类型(Ethernet)
        arp.hardtype = ARPPacket.HARDTYPE_ETHER;
        //选择IP网络协议类型
        arp.prototype = ARPPacket.PROTOTYPE_IP;
        //选择REPLY类型
        arp.operation = ARPPacket.ARP_REPLY;
        //MAC地址长度固定6个字节
        arp.hlen = 6;
        //IP地址长度固定4个字节
        arp.plen = 4;

        return arp;
    }

    /**
     * @param targetIp 目标
     * @param targetMac 目标
     * @param senderIp
     * @param senderMac
     */
    public static ARPPacket builder(
            String targetIp,
            String targetMac,
            String senderIp,
            String senderMac)  throws Exception{

        ARPPacket arp = ArpPacketBuilder.builder();

        //ip mac 转换
        InetAddress targetProtoAddr = InetAddress.getByName(targetIp);
        byte[] targetHardAddr = stomac(targetMac);
        InetAddress senderProtoAddr = InetAddress.getByName(senderIp);
        byte[] senderHardAddr = stomac(senderMac);

        arp.target_hardaddr = targetHardAddr;
        arp.target_protoaddr = targetProtoAddr.getAddress();

        arp.sender_hardaddr = senderHardAddr;
        arp.sender_protoaddr = senderProtoAddr.getAddress();

        // 设置DLC帧
        //创建一个以太网头
        EthernetPacket ether = new EthernetPacket();
        //选择以太包类型
        ether.frametype = EthernetPacket.ETHERTYPE_ARP;
        //将以太头添加到ARP包前
        arp.datalink = ether;
        //我的MAC地址
        ether.src_mac = senderHardAddr;
        //目标的MAC地址
        ether.dst_mac = targetHardAddr;

        return arp;
    }

    /**
     * mac字符串转mac byte[]
     * @param macString macString
     * @return mac
     */
    public static byte[] stomac(String macString) {

        byte[] mac = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 };
        String[] s1 = macString.split("-");
        for (int x = 0; x < s1.length; x++)
        {
            mac[x] = (byte) ((Integer.parseInt(s1[x], 16)) & 0xff);
        }
        return mac;
    }

}
